const user = require("../models/userDetail")

var express = require('express');
var router = express.Router();

const formidable = require('formidable');

router.post('/', (req, res, next) => {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({ 'state': false })
        } else {
            let target_userGroup = ''
            if (fields.flag === '助教') {
                target_userGroup = '2'
            } else if (fields.flag === '老师') {
                target_userGroup = '3'
            } else if (fields.flag === '学生') {
                target_userGroup = '0'
            } else if (fields.flag === '管理员') {
                target_userGroup = '1'
            }

            if (target_userGroup !== '') {
                user.updateMany({
                    UUID: {
                        $in: fields.selected
                    }
                }, {
                    $set: {
                        userGroup: target_userGroup
                    }
                }, (error, doc) => {
                    if (error) {
                        res.json({ 'state': false, 'msg': error });
                    } else {
                        res.json({ 'state': true, 'msg': "ok" });
                    }
                })
            } else {
                user.updateMany({
                    UUID: {
                        $in: fields.selected
                    }
                }, {
                        $addToSet: {
                            flags: fields.flag
                        }
                    }, (error, doc) => {
                        if (error) {
                            res.json({ 'state': false, 'msg': error });
                        } else {
                            res.json({ 'state': true, 'msg': "ok" });
                        }
                    }
                )
            }

        }

    });

});

module.exports = router;